// pages/history/history.js
const app = getApp();

Page({
  data: {
    historyList: [],
    loading: false,
    showEmpty: false
  },

  onLoad() {
    this.loadHistory();
  },

  onShow() {
    this.loadHistory();
  },

  onPullDownRefresh() {
    this.loadHistory();
    wx.stopPullDownRefresh();
  },

  // 加载历史记录
  loadHistory() {
    this.setData({ loading: true });
    
    try {
      const history = wx.getStorageSync('calculationHistory') || [];
      
      this.setData({
        historyList: history,
        showEmpty: history.length === 0,
        loading: false
      });
    } catch (error) {
      console.error('加载历史记录失败:', error);
      app.showError('加载历史记录失败');
      this.setData({ loading: false });
    }
  },

  // 查看历史记录详情
  viewHistoryDetail(e) {
    const index = e.currentTarget.dataset.index;
    const history = this.data.historyList[index];
    
    wx.navigateTo({
      url: `/pages/history-detail/history-detail?id=${history.id}`
    });
  },

  // 删除历史记录
  deleteHistory(e) {
    const index = e.currentTarget.dataset.index;
    const history = this.data.historyList[index];
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条计算记录吗？',
      success: (res) => {
        if (res.confirm) {
          this.confirmDelete(index);
        }
      }
    });
  },

  // 确认删除
  confirmDelete(index) {
    try {
      const historyList = [...this.data.historyList];
      historyList.splice(index, 1);
      
      wx.setStorageSync('calculationHistory', historyList);
      
      this.setData({
        historyList,
        showEmpty: historyList.length === 0
      });
      
      app.showSuccess('删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      app.showError('删除失败');
    }
  },

  // 清空所有历史记录
  clearAllHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有计算记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          this.confirmClearAll();
        }
      }
    });
  },

  // 确认清空所有
  confirmClearAll() {
    try {
      wx.removeStorageSync('calculationHistory');
      
      this.setData({
        historyList: [],
        showEmpty: true
      });
      
      app.showSuccess('清空成功');
    } catch (error) {
      console.error('清空失败:', error);
      app.showError('清空失败');
    }
  },

  // 分享历史记录
  shareHistory(e) {
    const index = e.currentTarget.dataset.index;
    const history = this.data.historyList[index];
    
    const shareText = `房贷计算记录：
贷款金额：${history.loanAmount}万元
贷款期限：${history.loanTerm}年
年利率：${history.interestRate}%
还款方式：${history.paymentMethod === 'equal_payment' ? '等额本息' : '等额本金'}
月供：¥${history.result.monthlyPayment.toFixed(2)}
总利息：¥${history.result.totalInterest.toFixed(2)}
总还款：¥${history.result.totalPayment.toFixed(2)}`;
    
    wx.setClipboardData({
      data: shareText,
      success: () => {
        app.showSuccess('记录已复制到剪贴板');
      }
    });
  },

  // 重新计算
  recalculate(e) {
    const index = e.currentTarget.dataset.index;
    const history = this.data.historyList[index];
    
    wx.navigateTo({
      url: `/pages/calculator/calculator?recalculate=true&data=${encodeURIComponent(JSON.stringify(history))}`
    });
  },

  // 格式化日期
  formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 格式化金额
  formatMoney(amount) {
    return (amount / 10000).toFixed(2) + '万';
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: '房贷计算器 - 历史记录',
      path: '/pages/history/history'
    };
  }
}); 